#!/usr/bin/env python
# @Author  : Bright (brt2@qq.com)
# @Create  : 2024-12-02
# @Update  : 2025-09-05 / 0.1.2

import os
import logging

_LOGGER_PATH = ""

def set_default_logpath(output_file=""):
    global _LOGGER_PATH

    _LOGGER_PATH = output_file

def make_logger(name, output_file=None, console=True, level=20):
    isExist = name in logging.Logger.manager.loggerDict
    logger = logging.getLogger(name)
    if isExist:
        # assert logger.level == level
        return logger

    logger.setLevel(level)  # logger_level must be lower than handler_level
    if console:
        import sys
        stdout_handler = logging.StreamHandler(sys.stdout)
        # stdout_handler.setLevel(logging.DEBUG)
        stdout_handler.setLevel(level)
        stdout_handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] [%(name)s::%(funcName)s::%(lineno)d] %(message)s"))
        logger.addHandler(stdout_handler)

    if output_file is None:
        output_file = _LOGGER_PATH
    if output_file:
        file_handler = logging.FileHandler(output_file, encoding='utf-8', mode='a')  # 追加模式
        file_handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s"))
        file_handler.setLevel(level)
        logger.addHandler(file_handler)

    return logger

def run_for_each_file(path, callback):
    # 如果是目录，遍历目录下所有文件，否则直接处理文件
    if os.path.isdir(path):
        from glob import glob

        print(">>> 当前路径为目录，将遍历目录下的所有文件")
        list_files = glob(os.path.join(path, "*"))
        for path_file in list_files:
            callback(path_file)
    elif os.path.isfile(path):
        callback(path)
    else:
        print(f"Error: File [{path}] NOT found.")

def read_as_multi_path(path_str):
    # 处理多文件路径
    path = path_str.strip()

    for q in ["\"", "\'"]:
        multi_files_gap = "{0} {0}".format(q)
        if path.find(multi_files_gap) >= 0:
            list_args = path.split(multi_files_gap)
            # break
            return [path.strip(q) for path in list_args]

    return [path.strip("\"").strip("\'")]
